package com.zmn.oms.zmn.business.impl.statistics;

import com.google.common.collect.Lists;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dro.statistics.UserOrderWarrantyStatDRO;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.oms.zmn.business.interfaces.statistics.StatOrderWarrantyBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 类描述：用户（手机号）订单保修状态统计
 *
 * @author liuyufan
 * @date 2021/12/3
 */
@Slf4j
@Service
public class StatOrderWarrantyBServiceImpl implements StatOrderWarrantyBService {

    @Autowired
    OrderWorkEsBService orderWorkEsBService;
    @Resource
    private OrderEncryptService orderEncryptService;

    @Override
    public UserOrderWarrantyStatDRO getUserWarrantyOrderStatByPhone(String phone) {
        log.info("订单统计-用户(手机号)保修状态订单统计，入参：{}", phone);
        // 过滤条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .filter(QueryBuilders.termQuery("contact.phone", orderEncryptService.encrypt(phone)))
                .filter(QueryBuilders.termQuery("isTest", false))
                .filter(QueryBuilders.termQuery("isDuplicate", false))
                // 业务规则：只要1和2
                .filter(QueryBuilders.termsQuery("type", Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW, OrderConsts.ORDER_TYPE_REWORK)));

        // 聚合操作
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(queryBuilder)
                .withPageable(Pageable.unpaged())
                //.withPageable(Pageable.unpaged())
                .withPageable(PageRequest.of(0, 1))
                .addAggregation(AggregationBuilders.filter("outWarrantyCount", QueryBuilders.boolQuery()
                        .filter(QueryBuilders.rangeQuery("warrantyProductMaxExpiredTime").lte(DateUtil.getNowFormatted()))))
                .addAggregation(AggregationBuilders.filter("inWarrantyCount", QueryBuilders.boolQuery()
                        .filter(QueryBuilders.rangeQuery("warrantyProductMaxExpiredTime").gt(DateUtil.getNowFormatted()))))
                .build();
        UserOrderWarrantyStatDRO userOrderWarrantyStatDRO = new UserOrderWarrantyStatDRO();
        Aggregations aggregations = orderWorkEsBService.getAggregationsByQuery(build);
        userOrderWarrantyStatDRO.setOrderCount(build.getMaxResults());
        Long inWarrantyCount = ((ParsedFilter) aggregations.get("inWarrantyCount")).getDocCount();
        userOrderWarrantyStatDRO.setInWarrantyCount(inWarrantyCount.intValue());

        Long doingOrderCount = ((ParsedFilter) aggregations.get("outWarrantyCount")).getDocCount();
        userOrderWarrantyStatDRO.setOutWarrantyCount(doingOrderCount.intValue());

        userOrderWarrantyStatDRO.setNoneWarrantyOrderCount(acountNoneWarranty(userOrderWarrantyStatDRO));

        log.info("订单统计-用户(手机号)保修状态订单统计，出参：{}", userOrderWarrantyStatDRO);
        return userOrderWarrantyStatDRO;
    }

    @Override
    public Long countInWarrantyOrderByUserIdList(List<Long> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            return 0L;
        }
        // 过滤条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .filter(QueryBuilders.termsQuery("userId", userIdList))
                .filter(QueryBuilders.termQuery("isTest", false))
                .filter(QueryBuilders.termQuery("isDuplicate", false))
                .filter(QueryBuilders.termsQuery("type", Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW, OrderConsts.ORDER_TYPE_REWORK)))
                .filter(QueryBuilders.rangeQuery("warrantyProductMaxExpiredTime").gt(DateUtil.getNowFormatted()));
        //queryBuilder.minimumShouldMatch(1);

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(queryBuilder)
                .withPageable(Pageable.unpaged()).build();

        Long count = orderWorkEsBService.countByQuery(build);
        return count;
    }

    private Integer acountNoneWarranty(UserOrderWarrantyStatDRO userOrderWarrantyStatDRO) {
        return userOrderWarrantyStatDRO.getOrderCount() -
                (userOrderWarrantyStatDRO.getInWarrantyCount() + userOrderWarrantyStatDRO.getOutWarrantyCount());
    }
}
